//
//  TuiJianViewController.m
//  TravelYo
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 TravelYo. All rights reserved.
//

#import "TuiJianViewController.h"


@interface TuiJianViewController () <SDCycleScrollViewDelegate>

// 轮播图数组
@property (nonatomic, strong) NSMutableArray *picsArray;

@property (nonatomic, strong) PicsModel *zhekouPic;


@property (nonatomic, strong) NSMutableArray *zhekouArray;

@property (nonatomic, strong) NSMutableArray *youjiArray;


@property (nonatomic, assign) BOOL isRefresh;

@property (nonatomic, assign) NSInteger pageNum;



@end


@implementation TuiJianViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // self.navigationController.navigationBar.backgroundColor = kMainColor;
    self.navigationItem.title = @"推荐";
    // self.navigationController.navigationBar.tintColor = kMainColor;
    
    // [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBar@2x.png.jpg"] forBarMetrics:UIBarMetricsDefault];
    
    _pageNum = 1;
    
    // self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    
    [self setUpRefresh];

    [self.tableView registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZhekouViewCell" bundle:nil] forCellReuseIdentifier:@"zhekouCell1"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ButtonsViewCell" bundle:nil] forCellReuseIdentifier:@"buttonsCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZheKouCell" bundle:nil] forCellReuseIdentifier:@"zhekouCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"zhekouTableViewCell" bundle:nil] forCellReuseIdentifier:@"zhekouCell2"];
   
    [self.tableView registerNib:[UINib nibWithNibName:@"KanYouJiViewCell" bundle:nil] forCellReuseIdentifier:@"kanyoujiCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"YoujiViewCell" bundle:nil] forCellReuseIdentifier:@"youjiCell"];
    
    
    
}


- (void)setUpRefresh
{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [self.tableView.header beginRefreshing];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.tableView.footer beginRefreshing];
    
}


- (void)headerRefresh
{
     _isRefresh = NO;
    self.picsArray = nil;
    self.zhekouArray = nil;
    self.zhekouPic = nil;
    self.youjiArray = nil;
    [self setUpData];
    [self.tableView.header endRefreshing];
}


- (void)footerRefresh
{
    _pageNum++;
    _isRefresh = YES;
    self.tableView.tableFooterView.hidden = YES;
    [self setUpData];
    [self.tableView.footer endRefreshing];
}
// 解析数据
- (void)setUpData
{
    
    __weak TuiJianViewController *mySelf = self;
    
    NSString *str = @"&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=3D292DEC-1F82-4FE7-9AE7-A1866F5F24E7&track_os=ios%25209.0.2&v=1";
    [[TYDataManager shareManager] requestDataWithUrl:[NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/entry?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=40.02934034260593&lon=116.3373160113825&page=%ld%@", _pageNum, str] block:^(NSData *data){
        NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *diction = dict[@"data"];
        NSArray *picarr = diction[@"slide"];
        _picsArray = nil;
        for (NSDictionary *dic in picarr) {
            PicsModel *model = [[PicsModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [mySelf.picsArray addObject:model];
        }
        // 折扣第一个图片
        NSArray *zhekouPicArr = diction[@"discount_subject"];
        for (NSDictionary *dic in zhekouPicArr) {
            [self.zhekouPic setValuesForKeysWithDictionary:dic];
        }
        
        NSArray *zhekouArr = diction[@"discount"];
        for (NSDictionary *dic in zhekouArr) {
            ZheKouModel *model = [[ZheKouModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.zhekouArray addObject:model];
        }
        [mySelf.tableView reloadData];
        
    }];
    NSString *str1 = @"&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=3D292DEC-1F82-4FE7-9AE7-A1866F5F24E7&track_os=ios%25209.0.2&type=index&v=1";
    [[TYDataManager shareManager] requestDataWithUrl:[NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&lat=40.0296984541268&lon=116.3376493226499&page=%ld%@", _pageNum, str1] block:^(NSData *data){
        
        NSMutableDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = diction[@"data"];
        for (NSDictionary *dic in array) {
            YouJiModel *model = [[YouJiModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.youjiArray addObject:model];
        }
        [mySelf.tableView reloadData];
    }];
    
}

// 游记数组懒加载
-(NSMutableArray *)youjiArray
{
    if (!_youjiArray) {
        _youjiArray = [NSMutableArray array];
    }
    return _youjiArray;
}



// 折扣数组懒加载
-(NSMutableArray *)zhekouArray
{
    if (!_zhekouArray) {
        _zhekouArray = [NSMutableArray array];
    }
    return _zhekouArray;
}


// 折扣图片懒加载
-(PicsModel *)zhekouPic
{
    if (!_zhekouPic) {
        _zhekouPic = [[PicsModel alloc] init];
    }
    return _zhekouPic;
}
//  轮播图数组懒加载
- (NSMutableArray *)picsArray
{
    
    if (!_picsArray) {
        _picsArray = [NSMutableArray array];
    }
    return _picsArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source 

// 表头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // 设置表头轮播图
    if (section == 0) {
        NSMutableArray *imageUrlArray = [NSMutableArray array];
        for (PicsModel *model in self.picsArray) {
            [imageUrlArray addObject:model.photo];
        }
        SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 180) imagesGroup:nil];
        cycleScrollView.imageURLStringsGroup = imageUrlArray;
        cycleScrollView.delegate = self;
        return cycleScrollView;
    } else {
        return nil;
    }

}




// 轮播图代理方法(点击跳转)
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
   // NSLog(@"%ld", index);
    ImageXQViewController *imageXQ = [[ImageXQViewController alloc] init];
    PicsModel *model = self.picsArray[index];
    imageXQ.url = model.url;
    // 跳转的时候隐藏navigationBar
    imageXQ.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:imageXQ animated:YES];
}

// 设置表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    if (section == 0) {
        return 180;
    } else {
        return 0;
    }
}

// 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 4;
}

// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        return 0;
    } else if (section == 1){
        return 1;
    } else if (section == 2) {
        return 4;
    } else  {
      return self.youjiArray.count;
    }
    
}


// cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return 90;
    } else if (indexPath.section == 2 && indexPath.row == 3) {
        return 44;
    } else if (indexPath.section == 3) {
        if (indexPath.row == 0) {
            return 30;
        } else {
        return 100;
        }
    }
    return 149;
}


// 自定义cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 1 && indexPath.row == 0) {
        ButtonsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"buttonsCell"];
        UIView *selecedView = [[UIView alloc] init];
        selecedView.backgroundColor = [UIColor whiteColor];
        cell.selectedBackgroundView = selecedView;
        [cell.kanjinnangBT addTarget:self action:@selector(actionKanjinNang:) forControlEvents:(UIControlEventTouchUpInside)];
        [cell.zhekouBT addTarget:self action:@selector(actionZhekou:) forControlEvents:(UIControlEventTouchUpInside)];
        [cell.jiudianBT addTarget:self action:@selector(actionJiuDian:) forControlEvents:(UIControlEventTouchUpInside)];
        
        // cell.userInteractionEnabled = NO;
        [cell.lvtuBT addTarget:self action:@selector(actionLvtu:) forControlEvents:(UIControlEventTouchUpInside)];
        return cell;
    } else if (indexPath.section == 2 && indexPath.row == 0) {
        // 折扣第一个图片
        ZhekouViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"zhekouCell1"];
         PicsModel *model = self.zhekouPic;
        UIView *selecedView = [[UIView alloc] init];
        selecedView.backgroundColor = [UIColor whiteColor];
        cell.selectedBackgroundView = selecedView;
         [cell.zhekouImage sd_setImageWithURL:[NSURL URLWithString:model.photo]];
        return cell;
    } else if (indexPath.section == 2 && indexPath.row != 0 && indexPath.row != 3) {
        
        ZheKouCell *cell = [tableView dequeueReusableCellWithIdentifier:@"zhekouCell"];
        if (self.zhekouArray.count > 0) {
            UIView *selecedView = [[UIView alloc] init];
            selecedView.backgroundColor = [UIColor whiteColor];
            cell.selectedBackgroundView = selecedView;
            ZheKouModel *modleOne = self.zhekouArray[indexPath.row - 1];
            ZheKouModel *modelTwo = self.zhekouArray[indexPath.row];
            [cell.imageOne sd_setImageWithURL:[NSURL URLWithString:modleOne.photo]];
            [cell.imageTwo sd_setImageWithURL:[NSURL URLWithString:modelTwo.photo]];
            
            cell.priceoffOne.text = modleOne.priceoff;
            cell.priceoffTwo.text = modelTwo.priceoff;
            NSString *textOne = [modleOne.price substringWithRange:NSMakeRange(4, modleOne.price.length - 11)];
            cell.priceOne.text = [textOne stringByReplacingOccurrencesOfString:@"<" withString:@""];
            NSString *textTwo = [modelTwo.price substringWithRange:NSMakeRange(4, modleOne.price.length - 11)];
            cell.priceTwo.text = [textTwo stringByReplacingOccurrencesOfString:@"<" withString:@""];
            cell.titleOne.text = modleOne.title;
            cell.titleTwo.text = modelTwo.title;
            
            [cell.button1 addTarget:self action:@selector(actionZhekouBT1:) forControlEvents:(UIControlEventTouchUpInside)];
            [cell.button2 addTarget:self action:@selector(actionZhekouBT2:) forControlEvents:(UIControlEventTouchUpInside)];
            cell.url1 = [NSString stringWithFormat:kZheKouAPI, modleOne.ID];
            cell.url2 = [NSString stringWithFormat:kZheKouAPI, modelTwo.ID];;
        }

        return cell;
    } else if (indexPath.section == 2 && indexPath.row == 3) {
        zhekouTableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:@"zhekouCell2"];
       
        // 设置cell选中时背景视图
        UIView *selecedView = [[UIView alloc] init];
        selecedView.backgroundColor = [UIColor whiteColor];
        cell.selectedBackgroundView = selecedView;
        cell.titleLabel.textColor = kMainColor;
      
        return cell;
    } else if (indexPath.section == 3) {
        if (indexPath.row == 0) {
            KanYouJiViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kanyoujiCell"];
            UIView *selecedView = [[UIView alloc] init];
            selecedView.backgroundColor = [UIColor whiteColor];
            cell.selectedBackgroundView = selecedView;
            return cell;      
        } else if (self.youjiArray.count > 0) {
            YouJiModel *model = self.youjiArray[indexPath.row];
            YoujiViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"youjiCell"];
            [cell.photoImage sd_setImageWithURL:[NSURL URLWithString:model.photo]];
            cell.titleLabel.text = model.title;
            cell.usernameLabel.text = model.username;
            cell.viewsLabel.text = [NSString stringWithFormat:@"查看数:%@", model.views];
            cell.replysLabel.text = [NSString stringWithFormat:@"回帖数:%@", model.replys];
            return cell;
        }
    }
    return nil;
}

// 点击cell方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2 && indexPath.row == 0) {
        ImageXQViewController *imageXQ = [[ImageXQViewController alloc] init];
        imageXQ.url = self.zhekouPic.url;
        // 跳转的时候隐藏navigationBar
        imageXQ.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:imageXQ animated:YES];
    } else if (indexPath.section == 2 && indexPath.row == 3) {
        QiangZheKouViewController *QZKVC = [[QiangZheKouViewController alloc] init];
        QZKVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:QZKVC animated:YES];
    } else if (indexPath.section == 3 && indexPath.row > 0) {
        YouJiModel *model = self.youjiArray[indexPath.row];
        ImageXQViewController *imageXQ = [[ImageXQViewController alloc] init];
        imageXQ.url = model.view_url;
        // 跳转的时候隐藏navigationBar
        imageXQ.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:imageXQ animated:YES];
    }
}

#pragma mark --- 点击四个按钮的方法
// 看锦囊
- (void)actionKanjinNang:(UIButton *)button
{
    KanJinNangViewController *jinNangVC = [[KanJinNangViewController alloc] init];
    jinNangVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:jinNangVC animated:YES];
}
// 看折扣
- (void)actionZhekou:(UIButton *)button
{
    QiangZheKouViewController *QZKVC = [[QiangZheKouViewController alloc] init];
    QZKVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:QZKVC animated:YES];
}
// 订酒店
- (void)actionJiuDian:(UIButton *)button
{
    DingJiuDianViewController *jiuDianVC = [[DingJiuDianViewController alloc] init];
    [self.navigationController pushViewController:jiuDianVC animated:YES];
}
// 旅途中
- (void)actionLvtu:(UIButton *)button
{
    CountrysViewController *countryVC = [[CountrysViewController alloc] init];
    // countryVC.hidesBottomBarWhenPushed = YES;
   // [self presentViewController:countryVC animated:YES completion:nil];
    countryVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:countryVC animated:YES];
}


#pragma mark --- 点击方法
- (void)actionZhekouBT1:(UIButton *)button
{
    ZheKouCell *cell = (ZheKouCell *)button.superview.superview;
   // NSLog(@"%@", cell.url1);
    ImageXQViewController *imageXQ = [[ImageXQViewController alloc] init];
    imageXQ.url = cell.url1;
    // 跳转的时候隐藏navigationBar
    imageXQ.hidesBottomBarWhenPushed = YES;
   
    [self.navigationController pushViewController:imageXQ animated:YES];
}
-(void)actionZhekouBT2:(UIButton *)button
{
    ZheKouCell *cell = (ZheKouCell *)button.superview.superview;
   // NSLog(@"%@", cell.url2);
    ImageXQViewController *imageXQ = [[ImageXQViewController alloc] init];
    imageXQ.url = cell.url2;
    // 跳转的时候隐藏navigationBar
    imageXQ.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:imageXQ animated:YES];

}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
